<template>
  <div class="news-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">本地资讯</h1>
      <p class="page-subtitle">发现本地优质资源和特色</p>
    </div>
    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input v-model="searchQuery" placeholder="输入关键字检索" size="large" clearable @input="handleSearch">
          <template #append>
            <el-icon @click="handleSearch" style="cursor: pointer"><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 筛选器 -->
      <div class="filters-row">
        <el-select v-model="selectedRating" placeholder="分类筛选" clearable @change="handleFilter" style="width: 120px">
          <el-option label="全部" value="" />
          <el-option label="科技" value="科技" />
          <el-option label="生活" value="生活" />
          <el-option label="财经" value="财经" />
          <el-option label="娱乐" value="娱乐" />
          <el-option label="旅游" value="旅游" />
        </el-select>

        <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort" style="width: 120px">
          <el-option label="综合排序" value="default" />
          <el-option label="点赞最高" value="rating" />
          <el-option label="浏览最多" value="distance" />
          <el-option label="最新发布" value="newest" />
        </el-select>
      </div>
    </div>

    <div class="news-cards" v-loading="loading">
      <el-empty v-if="list.length == 0" description="暂无数据" />
      <RouterLink :to="`/news/detail?id=${item.id}`" target="_blank" v-for="(item, index) in list" :key="index">
        <div class="news-card">
          <div class="cover" v-if="item.cover">
            <el-image :src="item.cover" fit="cover" style="width: 150px; height: 100px; border-radius: 5px" />
          </div>
          <div class="content">
            <div>
              <h2 class="news-title">{{ item.title }}</h2>
              <div class="news-subtitle">
                <span class="text-caption">{{ item.subTitle }}</span>
              </div>
              <div class="news-subtitle">
                <span class="text-caption">{{ item.summary }}</span>
              </div>
              <p class="news-location">{{ item.location }}</p>
              <p class="news-description text-sm">{{ item.description }}</p>
            </div>
            <div style="display: flex; justify-content: space-between">
              <div>
                <text class="news-time">{{ item.publishTime }}</text>
                <text class="news-views">{{ item.viewCount }} 阅读</text>
              </div>
              <div>
                <el-button @click.stop="showDetails(item)"> 查看详情 </el-button>
                <el-popconfirm title="你确定删除该数据" @confirm="handleRemove(item)" placement="top">
                  <template #reference>
                    <el-button type="warning" v-if="showAdminOpts" plain> 删除 </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </div>
        </div>
      </RouterLink>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background layout="prev, pager, next" :page-size="10" :total="totalCount" @change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue'
import { useHead } from '@vueuse/head'
import { fetchList, remove } from '@/apis/news'
import { Search } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const route = useRouter()

const showAdminOpts = computed(() => {
  return userStore.showAdminOpts ?? false
})

const handleRemove = (obj: any) => {
  // 处理删除逻辑
  remove(obj.id)
    .then((response) => {
      let { code, message } = response.data
      if (code !== 200) {
        throw new Error(message || '删除失败')
      }
      // 删除成功后重新获取数据
      fetchData()
    })
    .catch((error) => {
      console.error('删除失败:', error)
    })
}

useHead({
  title: '地方资讯 - 探索本地特殊',
  meta: [{ name: 'description', content: '探索您所在地区的资讯，发现最新旅游资料。' }]
})

const totalCount = ref(100) // 假设总职位数为1000
const searchQuery = ref('') // 搜索关键词
const listQuery = {
  page: 1,
  pageSize: 12,
  keyword: ''
}
const list = reactive<any>([])

const loading = ref(false)
const fetchData = () => {
  // 模拟获取数据
  listQuery.keyword = searchQuery.value.trim()
  loading.value = true
  fetchList(listQuery)
    .then((response) => {
      let { code, result, message } = response.data
      if (code !== 200) {
        throw new Error(message || '获取数据失败')
      }
      if (result.page) {
        list.splice(0, list.length) // 清空列表
      }
      totalCount.value = result.total
      list.splice(0, 0, ...result.items)
      // console.log('获取到的数据:', result.items[0])
    })
    .catch((error) => {
      console.error('获取数据失败:', error)
    })
    .finally(() => {
      loading.value = false
    })
}

const handleCurrentChange = (page: number, pageSize: number) => {
  // 这里可以添加分页逻辑
  listQuery.page = page
  listQuery.pageSize = pageSize
  fetchData()
  // console.log(`当前页: ${page}, 每页条数: ${pageSize}`)
}

onMounted(() => {
  fetchData()
})

const handleSearch = () => {
  // 处理搜索和排序
  fetchData()
}

const sortBy = ref<string>('default')
const selectedRating = ref<string>('')

const showDetails = (scene: any) => {
  route.push({
    path: `/news/detail`,
    query: {
      id: scene.id,
      target: '_blank'
    }
  })
}

const handleFilter = () => {
  // 这里可以添加筛选逻辑
}
const handleSort = () => {
  // 这里可以添加排序逻辑
}
</script>

<style scoped>
.news-list {
  max-width: var(--page-max-width);
  background-color: #f8fafc;
  padding: 20px;
  margin: 0px auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.page-header {
  width: 100%;
  text-align: center;
  margin-bottom: 30px;
}

.page-title {
  font-size: 1.5rem;
  font-weight: bold;
  color: #2563eb;
  margin-bottom: 10px;
}

.page-subtitle {
  font-size: 1.1rem;
  color: #6b7280;
  margin: 0;
}
.search-filter-section {
  width: 100%;
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.search-bar {
  margin-bottom: 20px;
}

.filters-row {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  align-items: center;
}

.news-cards {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 100%;
}

.news-card {
  display: flex;
  flex-direction: row;
  cursor: pointer;
  background-color: #eee;
  padding: 20px;
  transition: transform 0.3s;
  border-radius: 10px;
}
.cover {
  padding: 10px;
}
.content {
  display: flex;
  flex-direction: column;
  flex: 1;
}
.news-card:hover {
  transform: translateY(-5px);
}

.news-time,
.news-views {
  padding: 0px 10px;
  font-size: 22rpx;
  color: #94a3b8;
}
.news-title {
  font-size: 1.2rem;
  color: #333;
  margin-bottom: 10px;
}
.news-subtitle {
  font-size: 0.8rem;
  color: #666;
}
.news-location {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 10px;
}

.news-description {
  color: #888;
  margin-bottom: 15px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
</style>
